package cn.itsource.pethome.system.vcode.controller;

import cn.itsource.pethome.constants.BaseConstants;
import cn.itsource.pethome.system.vcode.domain.Vcode;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.SendMsgUtils;
import cn.itsource.pethome.utils.StrUtils;
import cn.itsource.pethome.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vcode")
//这里是说明你这个类是干什么用的
@Api(value = "验证码的API",description="验证码的功能")
public class CodeController {
    @Value("${msg_Uid}")
    private String msg_Uid;
    @Value("${msg_Key}")
    private String msg_Key;

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/imgCode/{key}")
    public AjaxResult getImgCode(@PathVariable String key){
        try {
            String code = StrUtils.getRandomString(6).toLowerCase();
            redisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);
            String base64Img = VerifyCodeUtils.VerifyCode(110, 40, code);
            return AjaxResult.success().setData(base64Img);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片验证码生成失败");
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        }
    }

    @PostMapping("/sendSmsCodeBind")
    public AjaxResult sendSmsCodeBind(@RequestBody Vcode vcode){
        String phone = vcode.getPhone();
        if(phone == null || "".equals(phone.trim())){
            return AjaxResult.error().setMsg("手机号不能为空!");
        }
        return sendSmsCode(phone,BaseConstants.Vcode.BIND,BaseConstants.Vcode.BIND_TIME,BaseConstants.Vcode.REGISTER_TIME_OUT);
    }

    private AjaxResult sendSmsCode(String phone,String businessKey,String businessKeyTime,long businessKeyTimeOut) {
        //手机验证我不做  你们去做
        String phoneCode = StrUtils.getRandomString(4).toLowerCase();//1234  4321

        String keyTime = phone + businessKeyTime;//获取上一次的时间
        //防止重复发送？？
        Object o = redisTemplate.opsForValue().get(keyTime);
        if (o == null) {
            //添加业务键标识
            long startTime = System.currentTimeMillis();
            String key = phone + businessKey;
            redisTemplate.opsForValue().set(key, phoneCode, businessKeyTimeOut, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(keyTime, startTime, businessKeyTimeOut, TimeUnit.MINUTES);
        } else {
            Long aLong = Long.valueOf(o.toString());
            long endTime = System.currentTimeMillis();//当前时间
            if (endTime - aLong < 60000) {
                return AjaxResult.error().setMsg("请勿重复获取验证码");
            } else {
                String key = phone + businessKey;
                //重置时间
                phoneCode = (String) redisTemplate.opsForValue().get(key);
                long startTime = System.currentTimeMillis();
                redisTemplate.opsForValue().set(key, phoneCode, businessKeyTimeOut, TimeUnit.MINUTES);
                redisTemplate.opsForValue().set(keyTime, startTime, businessKeyTimeOut, TimeUnit.MINUTES);
            }
        }

        //发送短信验证码
//        SendMsgUtils.sendMsg(msg_Uid,msg_Key,phone,phoneCode);
        System.err.println(phoneCode);
        return AjaxResult.success().setMsg("短信发送成功");
    }

    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody Vcode vcode){
        String imageCodeKey = vcode.getImageCodeKey();
        String phone = vcode.getPhone();
        String imageCode = vcode.getImageCode();
        //参数校验
        if(imageCodeKey == null || "".equals(imageCodeKey.trim())){
            return AjaxResult.error().setMsg("非法访问!");
        }
        if(phone == null || "".equals(phone.trim())){
            return AjaxResult.error().setMsg("手机号不能为空!");
        }
        if(imageCode == null || "".equals(imageCode.trim())){
            return AjaxResult.error().setMsg("验证码不能为空!");
        }
        //前置条件
        //验证码校验
        Object value = redisTemplate.opsForValue().get(imageCodeKey);
        if(value == null){//看验证码有没有失效
            return AjaxResult.error().setMsg("图片验证码已失效,请重新xxx");
        }
        if(!value.toString().equals(imageCode)){//判断用户输入的验证码对不对
            return AjaxResult.error().setMsg("验证码输出错误!");
        }
        //手机验证我不做  你们去做
        return sendSmsCode(phone,BaseConstants.Vcode.REGISTER,BaseConstants.Vcode.REGISTER_TIME,BaseConstants.Vcode.REGISTER_TIME_OUT);
    }
}
